package com.cs.common.zip;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Unzip {
    /**
     * 解压到文件夹
     */
    public static void unzip2Folder (String zipFileName, String unzipPathName) throws IOException {
        //创建解压缩文件保存的路径
        File unzipFileDir = new File(unzipPathName);
        if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
            unzipFileDir.mkdirs();
        }

        //开始解压
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        File zipFile = new File(zipFileName);
        ZipFile zip = new ZipFile(zipFile);
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
        //循环对压缩包里的每一个文件进行解压
        while(entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //构建压缩包中一个文件解压后保存的文件全路径
            String entryFilePath = unzipPathName + File.separator + entry.getName();
            //构建解压后保存的文件夹路径
            int index = entryFilePath.lastIndexOf(File.separator);
            String entryDirPath = "";
            if (index != -1) {
                entryDirPath = entryFilePath.substring(0, index);
            }
            File entryDir = new File(entryDirPath);
            //如果文件夹路径不存在，则创建文件夹
            if (!entryDir.exists() || !entryDir.isDirectory()) {
                entryDir.mkdirs();
            }

            //创建解压文件
            File entryFile = new File(entryFilePath);

            //写入文件
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(entryFile));
            bufferedInputStream = new BufferedInputStream(zip.getInputStream(entry));
            int buff;
            while ( ( buff=bufferedInputStream.read()) != -1 ) {
                bufferedOutputStream.write(buff);
            }
            bufferedOutputStream.close();
            bufferedInputStream.close();
        }
    }
}
